package com.atguigu.guli.service.oss.controller.admin;

import com.atguigu.commonutils.ExceptionUtils;
import com.atguigu.commonutils.ResultCodeEnum;
import com.atguigu.commonutils.result.R;
import com.atguigu.guli.service.base.Exception.GuliException;
import com.atguigu.guli.service.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author: Mr.Wang
 * @date: 2021-05-16 20:39
 * @description:
 */
@Api(tags = "阿里云文件上传管理")
@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/admin/oss/file")
public class FileController {
    @Autowired
    private FileService fileService;

    @PostMapping("upload")
    public R upload(
            @ApiParam(value = "文件",required = true)
            @RequestParam("file")MultipartFile file,
            @ApiParam(value = "模块",required = true)
            @RequestParam("module") String module
            ){
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String uploadUrl = fileService.upload(inputStream,module,originalFilename);
            return R.ok().message("文件上传成功").data("url",uploadUrl);
        } catch (IOException e) {
           log.error(ExceptionUtils.getMessage(e));
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }

    }

    @ApiOperation("删除讲师的图片链接")
    @DeleteMapping("/remove")
    public R removeFile(
            @ApiParam(value = "需要删除的图片的url",required = true)
            @RequestBody String url
    ) {
        fileService.removeFile(url);
        return R.ok().message("文件删除成功");
    }
    @ApiOperation("openFeign的测试例子")
    @GetMapping("/test")
    public R test() {
        log.info("oss test方法被调用");
        return R.ok();
    }

}
